# server.awk v1.01 - Michael S. Sanders 2009
# license: GPL3
#
# a simple, single user, web server built with gawk
# updates at: http://topcat.hypermart.net/index.html
#
# creates an html menu of local applications - season to taste...
# usage requires two steps...
#
# 1. run: 'gawk -f server.awk'
# 2. open browser at: http://localhost:8080 
#
# based on the examples located at:
# http://www.gnu.org/software/gawk/manual/gawkinet/gawkinet.html


BEGIN {
  x        = 1                        # script exits if x < 1
  port     = 8080                     # port number
  host     = "/inet/tcp/" port "/0/0" # host string
  url      = "http://localhost:" port # server url
  RS = ORS = "\r\n"                   # header line terminators
  doc      = Setup()                  # html document

  while (x) {
  if ($1 == "GET") RunApp(substr($2, 2))
  if (! x) break
  Message(doc)
  host |& getline # wait for new client request
  }

  Message(Bye())  # server terminated...

}

# ----------------------------------------------------------------------

function Message(txt) {

  status = 200                       # 200 == OK
  reason = "OK"                      # server response
  len    = length(txt) + length(ORS) # length of document

  print "HTTP/1.0", status, reason |& host
  print "Connection: Close"        |& host
  print "Pragma: no-cache"         |& host
  print "Content-length:", len     |& host
  print ORS txt                    |& host
  close(host)

}

# ----------------------------------------------------------------------

function RunApp(app) {

  if (app == "xterm") {system("xterm&"); return}
  if (app == "xcalc") {system("xcalc&"); return}
  if (app == "xload") {system("xload&"); return}
  if (app == "exit")  {x = 0}

}

# ----------------------------------------------------------------------

function Setup(tmp) {

  tmp = "<html>\
  <head><title>Simple gawk server</title></head>\
  <body>\
  <p><a href=" url "/xterm>xterm</a>\
  <p><a href=" url "/xcalc>xcalc</a>\
  <p><a href=" url "/xload>xload</a>\
  <p><a href=" url "/exit>terminate script</a>\
  </body>\
  </html>"

  return tmp

}

# ----------------------------------------------------------------------

function Bye(tmp) {

  tmp = "<html>\
  <head><title>Simple gawk server</title></head>\
  <body><p>Script Terminated...</body>\
  </html>"

return tmp

}

# eof
